package handler

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"travel-app/api/client"
	"travel-app/api/model"
	"travel-app/common/proto/user"
	"travel-app/pkg"
)

func Register(c *gin.Context) {
	var data model.User
	if err := c.ShouldBind(&data); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 0,
			"msg":  err.Error(),
			"data": nil,
		})
		return
	}
	login, err := client.Register(c, &user.RegisterReq{
		Mobile:   data.Mobile,
		Password: data.Password,
	})
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 0,
			"msg":  err.Error(),
			"data": nil,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "用户注册成功",
		"data": login,
	})
}

func Login(c *gin.Context) {
	var data model.User
	if err := c.ShouldBind(&data); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 0,
			"msg":  err.Error(),
			"data": nil,
		})
		return
	}
	login, err := client.Login(c, &user.LoginReq{
		Mobile:   data.Mobile,
		Password: data.Password,
	})
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 0,
			"msg":  err.Error(),
			"data": nil,
		})
		return
	}

	claims := pkg.CustomClaims{
		ID: uint(login.Id),
	}

	token, err := pkg.NewJWT("2209a").CreateToken(claims)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 0,
			"msg":  "token生成错误",
			"data": nil,
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "用户登陆成功",
		"data": token,
	})
}

func UserReal(c *gin.Context) {
	var data model.UserReal
	if err := c.ShouldBind(&data); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 0,
			"msg":  err.Error(),
			"data": nil,
		})
		return
	}
	login, err := client.UserReal(c, &user.UserRealReq{
		Name: data.Name,
		Card: data.Card,
	})
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 0,
			"msg":  err.Error(),
			"data": nil,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "用户实名认证成功",
		"data": login,
	})
}
